package com.sanbi.erp.api.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSONObject;
import com.sanbi.common.util.JacksonUtil;
import com.sanbi.common.vo.PageListVo;
import com.sanbi.common.vo.ResponseVo;
import com.sanbi.erp.core.system.ErrorEnum;
import com.sanbi.erp.core.util.DownLoadFileUtils;
import com.sanbi.erp.core.util.OkHttpUtil;
import com.sanbi.erp.core.vo.PNGUploadRespVo;
import com.sanbi.erp.db.config.BizException;
import com.sanbi.erp.db.domain.*;
import com.sanbi.erp.db.service.LogService;
import com.sanbi.erp.db.service.ProcurementPlanService;
import com.sanbi.erp.db.service.ProductService;
import com.sanbi.erp.db.util.CheckoutUtil;
import com.sanbi.erp.db.util.easyExcel.EasyExcelListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.System;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @introduce: 采购计划服务
 * @Date: 2022/11/7 11:42
 * @Author: XYP
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/erp/procurementPlan")
public class ErpProcurementPlanController {
    @Resource
    ProcurementPlanService procurementPlanService;

    @Resource
    ProductService productService;
    @Resource
    LogService logService;

    // excel文件存本地储地址
    @Value("${easyExcel.qrcodeLocalPathXlsl}")
    private String qrcodeLocalPathXlsl;
    // 文件服务器地址
    @Value("${easyExcel.defaultFileServer}")
    private String defaultFileServer;

    /**
     * 查询商品信息 新增采购计划时使用
     * @param body 查询条件
     * {detailsType 1 单个商品sku  2 组合商品sku,
     *  matching   1 精确匹配 2 模糊匹配,
     *  message 查询内容}
     * @return
     */
    @PostMapping("/getListByProductSku")
    public ResponseVo<List<Product>> getListByProductSku(@RequestBody String body) {
        return ResponseVo.ok(this.productService.getListByProductSku(body));
    }

    /**
     * 创建采购计划
//     * @param adminId 当前管理员id
     * @param list 采购计划集合
     * @return
     */
    @PostMapping("/addList")
    public ResponseVo<Integer> addList(@RequestBody List<ProcurementPlan> list) {
        // return ResponseVo.ok();
        // @RequestParam Integer adminId
        Integer adminId = 1;
        if (list.size() <= CheckoutUtil.TYPE_ZERO || CheckoutUtil.isEmptyInteger(adminId)) {
            throw new BizException(ErrorEnum.ErrorCode.BadReqArgument);
        }
        return ResponseVo.ok(this.procurementPlanService.addList(adminId,list));
    }

    /**
     * 获取采购计划信息
     * @param body 查询条件
     * {matching  0 默认 1 精确匹配 2 模糊匹配,
     *  detailsType 0 默认 1 库存sku 3 中文名称 5 供应商,
     *  message 查询内容,
     *  planState sku状态 0 全部 1001 待审核，1002 同意，1003 拒绝,
     *  beginTime 开始时间,
     *  endTime 结束时间,
     *  page 页索引,
     *  limit 页大小}
     * @return
     */
    @PostMapping("/getList")
    public ResponseVo<PageListVo<ProcurementPlan>> getList(@RequestBody String body) {
        Integer page = JacksonUtil.parseInteger(body, "page");
        Integer limit = JacksonUtil.parseInteger(body, "limit");
        if (!ObjectUtils.allNotNull(page, limit)) {
            throw new BizException(ErrorEnum.ErrorCode.BadReqArgument);
        }
        return ResponseVo.okList(this.procurementPlanService.selectLinkList(body,page,limit));
    }

    /**
     * 同意采购/批量同意
     * @param list 采购计划id集合
     * @return
     */
    @PostMapping("/consentProcurementPlan")
    public ResponseVo<Integer> consentProcurementPlan(@RequestParam List<Integer> list){
        if (list.size() <= CheckoutUtil.TYPE_ZERO) {
            throw new BizException(ErrorEnum.ErrorCode.BadReqArgument);
        }
        Integer adminId = 1;
        return ResponseVo.ok(this.procurementPlanService.updateById(list,adminId));
    }

    /**
     * 拒绝采购/批量拒绝采购
     * @param list 采购计划id集合
     * @param desc 拒绝原因
     * @return
     */
    @PostMapping("/refuseProcurementPlan")
    public ResponseVo<Integer> refuseProcurementPlan(@RequestParam List<Integer> list,@RequestParam String desc){
        Integer adminId = 1;
        return ResponseVo.ok(this.procurementPlanService.updateRefuseById(list,desc,adminId));
    }

    /**
     * 重新修改
     * @param procurementPlanId 采购计划id
     * @param procurementPlanCount 采购数量
     * @return
     */
    @GetMapping("/updateProcurementPlan")
    public ResponseVo<Integer> updateProcurementPlan(@RequestParam Integer procurementPlanId,@RequestParam Integer procurementPlanCount){
        if (CheckoutUtil.isEmptyInteger(procurementPlanId)) {
            throw new BizException(ErrorEnum.ErrorCode.BadReqArgument);
        }
        Integer adminId = 1;
        return ResponseVo.ok(this.procurementPlanService.updateByIdTwo(procurementPlanId,procurementPlanCount,adminId));
    }

    /**
     * 审核详情
     * @param procurementPlanId 采购计划id
     * @return
     */
    @GetMapping("/procurementPlanDetails")
    public ResponseVo<List<Log>> procurementPlanDetails(@RequestParam Integer procurementPlanId){
        if (CheckoutUtil.isEmptyInteger(procurementPlanId)) {
            throw new BizException(ErrorEnum.ErrorCode.BadReqArgument);
        }
        return ResponseVo.ok(logService.selectList(procurementPlanId));
    }

    /**
     * 批量删除
     * @param list 采购计划id集合
     * @return
     */
    @PostMapping("/deleteList")
    public ResponseVo<Integer> deleteList(@RequestParam List<Integer> list){
        if (list.size() <= CheckoutUtil.TYPE_ZERO) {
            throw new BizException(ErrorEnum.ErrorCode.BadReqArgument);
        }
        return ResponseVo.ok(procurementPlanService.updateByIdList(list));
    }

    /**
     * 批量导入采购计划
     * 从Excel表格读取数据
     * @param filePath 阿里云文件存储地址
     * @return
     */
    @GetMapping("/addProcurementPlanExcel")
    public ResponseVo<String> addProcurementPlanExcel(@RequestParam String filePath) {
        // 截取文件名称
        String filePathTwo = StringUtils.substringBefore(filePath, "?");
        String oneString = StringUtils.substringAfterLast(filePath, "/");
        String twoString = StringUtils.substringBefore(oneString, "?");
        String path = qrcodeLocalPathXlsl + twoString;
        // 文件保存到本地
        try{
            DownLoadFileUtils.downLoadByUrl(filePathTwo,qrcodeLocalPathXlsl);
        }catch (Exception e) {
            e.printStackTrace();
        }
        // String path = "C:\\Users\\23026\\Desktop\\erp1.xlsx";
        ExcelReader build = EasyExcel.read(path,ProcurementPlanEasyExcelAdd.class, new EasyExcelListener()).build();
        ReadSheet buildOne = EasyExcel.readSheet(0).build();
        build.read(buildOne);
        return ResponseVo.ok();
    }

    /**
     * 导出采购计划信息
     * @param body 查询条件
     * {matching  0 默认 1 精确匹配 2 模糊匹配,
     *  detailsType 0 默认 1 库存sku 3 中文名称 5 供应商,
     *  message 查询内容,
     *  planState sku状态 0 全部 1001 待审核，1002 同意，1003 拒绝,
     *  beginTime 开始时间,
     *  endTime 结束时间,
     *  page 页索引,
     *  limit 页大小}
     * @return
     */
    @PostMapping("/batchDeriveExcel")
    public ResponseVo<Map<String,String>> batchDeriveExcel(@RequestBody String body) {
        Integer page = JacksonUtil.parseInteger(body, "page");
        Integer limit = JacksonUtil.parseInteger(body, "limit");
        if (!ObjectUtils.allNotNull(page, limit)) {
            throw new BizException(ErrorEnum.ErrorCode.BadReqArgument);
        }
        // 导出的excel文件，本地存储地址
        long l = System.currentTimeMillis();
        String fileName = qrcodeLocalPathXlsl + l + ".xlsx";
        // String fileName = "C:\\Users\\23026\\Desktop\\" + "erp" + l + ".xlsx";
        String nameTwo = String.format("%s.xlsx",l); // 文件名称带后缀
        EasyExcel.write(fileName, ProcurementPlanEasyExcelDerive.class)
                .sheet("模板")
                .doWrite(() -> {return this.procurementPlanService.batchDeriveExcel(body,page,limit);});
        // 【上传到文件服务器】
        String postPNG = OkHttpUtil.postPNG(defaultFileServer, fileName, nameTwo);
        // 解析返回结果，得到上传成功的远程文件路径 http://...
        PNGUploadRespVo pdfUploadResp = JSONObject.parseObject(postPNG, PNGUploadRespVo.class);
        // log.info("{}筛选导出文件链接地址url",pdfUploadResp.getData());
        Map<String,String> map = new HashMap<>();
        map.put("desc","筛选导出文件链接地址");
        map.put("url",pdfUploadResp.getData());
        return ResponseVo.ok(map);
    }

    /**
     * 导出采购计划信息(选择导出)
     * @return
     */
    @PostMapping("/batchDeriveExcelGroupById")
    public ResponseVo<Map<String,String>> batchDeriveExcelGroupById(@RequestBody List<Integer> list) {
        // 导出的excel文件，本地存储地址
        long l = System.currentTimeMillis();
        String fileName = qrcodeLocalPathXlsl + l + ".xlsx";
        // String fileName = "C:\\Users\\23026\\Desktop\\" + "erp" + l + ".xlsx";
        String nameTwo = String.format("%s.xlsx",l); // 文件名称带后缀
        EasyExcel.write(fileName, ProcurementPlanEasyExcelDerive.class)
                .sheet("模板")
                .doWrite(() -> {return this.procurementPlanService.batchDeriveExcelGroupById(list);});
        // 【上传到文件服务器】
        String postPNG = OkHttpUtil.postPNG(defaultFileServer, fileName, nameTwo);
        // 解析返回结果，得到上传成功的远程文件路径 http://...
        PNGUploadRespVo pdfUploadResp = JSONObject.parseObject(postPNG, PNGUploadRespVo.class);
        // log.info("{}筛选导出文件链接地址url",pdfUploadResp.getData());
        Map<String,String> map = new HashMap<>();
        map.put("desc","筛选导出文件链接地址");
        map.put("url",pdfUploadResp.getData());
        return ResponseVo.ok(map);
    }
}
